package com.yicun.companyapplication;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.GravityCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.yicun.HttpUtils.OkHttpUtil;
import com.yicun.adapter.CompanyAdapter;
import com.yicun.adapter.PhoneAdapter;
import com.yicun.fragment.RegionSelectorFragment;
import com.yicun.gloable.API;
import com.yicun.model.ApiResponse;
import com.yicun.model.Company;
import com.yicun.model.CompanyPhone;
import com.yicun.utils.DateUtils;
import com.yicun.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private RecyclerView recyclerView;
    private CompanyAdapter companyAdapter;
    private Button btnPrev, btnNext;
    private TextView tvPageInfo;
    private TextView tvTotalCount;
    private int currentPage = 1;
    private final int pageSize = 10;

    private int total=0;

    int totalPage=0;
    private String selectedProvince = "";
    private String selectedCity = "";
    private String selectedDistrict = "";

    private String setBusinessScope;

    private Boolean isOnlyShowStar=false;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int i = msg.what;
            if (i == 3) {
                loadSuccess((String) msg.obj);
            }
            return false;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        // 初始化视图
        initViews();

        // 设置工具栏和抽屉
        setupToolbar();
        setupDrawer();

        // 设置RecyclerView
        setupRecyclerView();

        // 设置分页按钮
        setupPagination();

        // 加载初始数据
        reqCountData();
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });
    }
    private void initViews() {
        drawerLayout = findViewById(R.id.drawer_layout);
        recyclerView = findViewById(R.id.recycler_view);
        btnPrev = findViewById(R.id.btn_prev);
        btnNext = findViewById(R.id.btn_next);
        tvPageInfo = findViewById(R.id.tv_page_info);
        tvTotalCount=findViewById(R.id.tv_total_count);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void setupDrawer() {
        drawerToggle = new ActionBarDrawerToggle(
                this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
        drawerLayout.addDrawerListener(drawerToggle);
        drawerToggle.syncState();

        // 设置抽屉内容
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.drawer_content, new RegionSelectorFragment())
                .commit();
    }

    private void setupRecyclerView() {
        companyAdapter = new CompanyAdapter(new ArrayList<>());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(companyAdapter);
        // 设置点击事件
        companyAdapter.setOnItemClickListener(company -> {
            // 跳转到详情页面或显示更多信息
            showCompanyDetails(company);
        });
        companyAdapter.setOnStarClickListener(new CompanyAdapter.OnStarClickListener() {
            @Override
            public void onStarClick(Company company, int position) {
                toggleStar(company,position);
            }
        });
    }

    private void setupPagination() {
        btnPrev.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                reqCountData();
            }
        });

        btnNext.setOnClickListener(v -> {
            if(currentPage<totalPage){
                currentPage++;
                reqCountData();
            }else {
                Toast.makeText(this,"没有下一页了",Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void loadSuccess(String str) {

        // 解析JSON
        ApiResponse apiResponse = new Gson().fromJson(str, ApiResponse.class);

// 使用解析后的数据
        if (apiResponse != null && apiResponse.getCode() == 200) {
            total=apiResponse.getData().getCount();
            totalPage=total/10+1;
            tvTotalCount.setText("共"+total+"条数据");
            List<Company> companies = apiResponse.getData().getList();
            companyAdapter.updateData(companies);
            updatePageInfo();
        }

    }

    private void updatePageInfo() {
//        String statusText = String.format("状态: %s | 注册资本: %s万 | 参保人数: %s人" ,
//                company.getBusinessStatus(),
//                StringUtils.formatCapital(company.getRegisteredCapital()),company.getInsuredCount());

        tvPageInfo.setText(String.format(Locale.getDefault(), "第 %d/%d 页", currentPage,totalPage));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // 从Fragment接收地区选择
    public void onRegionSelected(String province, String city, String district,String businessScope,Boolean onlyShowStar) {
        selectedProvince = province;
        selectedCity = city;
        selectedDistrict = district;
        setBusinessScope =businessScope;
        isOnlyShowStar=onlyShowStar;
        currentPage = 1; // 重置为第一页
        reqCountData();
        drawerLayout.closeDrawer(GravityCompat.START);
    }
    private void reqCountData() {
        //  try {
        HashMap hashMap = new HashMap();
        hashMap.put("currPage",currentPage);
        hashMap.put("pageSize", 10);
        hashMap.put("province", selectedProvince);
        hashMap.put("city", selectedCity);
        hashMap.put("district", selectedDistrict);
        hashMap.put("businessScope",setBusinessScope);
        if(isOnlyShowStar){
            hashMap.put("isStar","1");
        }
        OkHttpUtil.getInstance().postAsynPostJson(API.CompanyDataReq, hashMap, new OkHttpUtil.OnCallback() { // from class: com.example.MoJuGuiDingZhi.HomeActivity.14
            @Override // com.example.MoJuGuiDingZhi.HttpUtils.OkHttpUtil.OnCallback
            public void callback(String str2) {
                Log.d("测试",str2);
                Message message = new Message();
                message.obj = str2;
                message.what = 3;
                mHandler.sendMessage(message);
            }

            @Override // com.example.MoJuGuiDingZhi.HttpUtils.OkHttpUtil.OnCallback
            public void onFailure(String str2) {
                Message message = new Message();
                message.obj = str2;
                message.what = 4;
                mHandler.sendMessage(message);
            }
        });
//        } catch (Exception unused) {
//            ToastUtils.show(this, "http请求头配置错误");
//        }
    }
    private void toggleStar(Company company,int position) {
        //  try {
        HashMap hashMap = new HashMap();
        hashMap.put("id",company.getId());
        if(company.getIsStar().equals("1")){
            hashMap.put("isStar","0");
        }else {
            hashMap.put("isStar","1");
        }

        OkHttpUtil.getInstance().postAsynPostJson(API.CompanyStar, hashMap, new OkHttpUtil.OnCallback() { // from class: com.example.MoJuGuiDingZhi.HomeActivity.14
            @Override // com.example.MoJuGuiDingZhi.HttpUtils.OkHttpUtil.OnCallback
            public void callback(String str2) {
               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       companyAdapter.toggleStar(position);
                   }
               });
            }

            @Override // com.example.MoJuGuiDingZhi.HttpUtils.OkHttpUtil.OnCallback
            public void onFailure(String str2) {

            }
        });
    }
    private void showCompanyDetails(Company company) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(company.getCompanyName());

//        // 创建详细信息的HTML格式内容
//        String htmlContent = "<b>统一信用代码:</b> " + company.getCreditCode() + "<br><br>" +
//                "<b>注册地址:</b> " + company.getRegisteredAddress() + "<br><br>" +
//                "<b>成立日期:</b> " + DateUtils.formatDate(company.getEstablishmentDate()) + "<br><br>" +
//                "<b>注册资本:</b> " + StringUtils.formatCapital(company.getRegisteredCapital()) + "万元<br><br>" +
//                "<b>经营范围:</b><br>" + company.getBusinessScope()+"<br><br>"+"<b>更多联系号码:</b><br>";
        // 高亮经营范围中与 setBusinessScope 匹配的部分
        String businessScope = company.getBusinessScope();
        if (setBusinessScope != null && !setBusinessScope.isEmpty()) {
            // 使用正则表达式匹配（不区分大小写）
            businessScope = businessScope.replaceAll(
                    "(?i)(" + Pattern.quote(setBusinessScope) + ")",
                    "<font color='red'>$1</font>"
            );
        }

        // 创建详细信息的HTML格式内容
        String htmlContent = "<b>统一信用代码:</b> " + company.getCreditCode() + "<br><br>" +
                "<b>注册地址:</b> " + company.getRegisteredAddress() + "<br><br>" +
                "<b>成立日期:</b> " + DateUtils.formatDate(company.getEstablishmentDate()) + "<br><br>" +
                "<b>注册资本:</b> " + StringUtils.formatCapital(company.getRegisteredCapital()) + "万元<br><br>" +
                "<b>经营范围:</b><br>" + businessScope + "<br><br>" +
                "<b>更多联系号码:</b><br>";

        for(CompanyPhone companyPhone:company.getMorePhones()){
            htmlContent+=companyPhone.getPhoneNumber()+"<br><br>";
        }
        // 使用WebView显示格式化内容
        WebView webView = new WebView(this);
        webView.loadData(htmlContent, "text/html", "UTF-8");

        builder.setView(webView);
        builder.setPositiveButton("关闭", (dialog, which) -> dialog.dismiss());

        // 添加查看官网按钮（如果有网站）
        if (!TextUtils.isEmpty(company.getWebsite()) &&
                company.getWebsite().startsWith("http")) {
            builder.setNeutralButton("访问官网", (dialog, which) -> {
                Uri uri = Uri.parse(company.getWebsite());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            });
        }

        AlertDialog dialog = builder.create();
        dialog.show();

        // 调整对话框大小
        Window window = dialog.getWindow();
        if (window != null) {
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }
}